/*
 * Copyright (c) 2021-2031, 河北计全科技有限公司 (https://www.jeequan.com & jeequan@126.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.splic.api.controller.product;

import com.alibaba.fastjson.JSONObject;
import com.splic.common.enums.OrderStatusEnum;
import com.splic.common.exception.BusinessException;
import com.splic.common.utils.SpringBeansUtil;
import com.splic.product.domain.Order;
import com.splic.product.service.OrderService;
import com.splic.product.service.PayNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


@Slf4j
@RestController
@RequestMapping("/api/payNotify")
public class ApiPayNotifyController {

    @Autowired
    private OrderService orderServiceImpl;

    /**
     * 支付宝支付回调
     * @param request
     * @return
     */
    @RequestMapping("/aliPayNotify")
    public String aliPayNotify(HttpServletRequest request){

        String orderNo = null;
        log.info("进入[:{}]支付同步跳转]" );
        log.info("=======回调原始数据==========:{}",JSONObject.toJSONString(request.getParameterMap()));

        try {

            //查询支付接口是否存在
            PayNotifyService payNotifyService = SpringBeansUtil.getBean("alipayNotifyService", PayNotifyService.class);

            // 支付通道接口实现不存在
            if(payNotifyService == null){
                log.error("{}, interface not exists ", payNotifyService);
                throw new BusinessException("支付类型不存在！");
            }

            // 解析订单号 和 请求参数
            MutablePair<String, Object> mutablePair = payNotifyService.parseParams(request, PayNotifyService.NoticeTypeEnum.DO_NOTIFY);
            if(mutablePair == null){ // 解析数据失败， 响应已处理
                log.error("{}, mutablePair is null ", mutablePair);
                throw new BusinessException("解析数据异常！"); //需要实现类自行抛出ResponseException, 不应该在这抛此异常。
            }
            //解析到订单号
            orderNo = mutablePair.left;
            log.info("解析数据为：orderNo:{}, params:{}", orderNo, mutablePair.getRight());

            //获取订单号 和 订单数据
            Order payOrder = orderServiceImpl.getByOrderNo(orderNo);

            // 订单不存在
            if(payOrder == null){
                log.error("订单不存在. orderNo={} ",orderNo);
                return "fail";
            }

            if (Objects.equals(OrderStatusEnum.PAY_SUCCESS,payOrder.getStatus())){
                return "success";
            }

            //调起接口的回调判断
            payNotifyService.doNotice(request, mutablePair.getRight(), payOrder, PayNotifyService.NoticeTypeEnum.DO_RETURN);

            log.error("=====, 订单通知完成。 orderNo={} =====",orderNo);
            return "success";
        } catch (BusinessException e) {
            log.error("业务处理异常, orderNo={}, BizException:{}", orderNo, e);
            return "fail";

        } catch (Exception e) {
            log.error("回调失败, orderNo={}, 系统异常", orderNo, e);
            return "fail";
        }
    }



    /**
     * 微信支付回调
     * @param request
     * @return
     */
    @RequestMapping("/wxPayNotify")
    public String wxPayNotify(HttpServletRequest request){

        String orderNo = null;
        log.info("进入[:{}]支付同步跳转]" );
        log.info("=======回调原始数据==========:{}",JSONObject.toJSONString(request.getParameterMap()));

        try {

            //查询支付接口是否存在
            PayNotifyService payNotifyService = SpringBeansUtil.getBean( "wxpayNotifyService", PayNotifyService.class);

            // 支付通道接口实现不存在
            if(payNotifyService == null){
                log.error("{}, interface not exists ", payNotifyService);
                throw new BusinessException("支付类型不存在！");
            }

            // 解析订单号 和 请求参数
            MutablePair<String, Object> mutablePair = payNotifyService.parseParams(request, PayNotifyService.NoticeTypeEnum.DO_NOTIFY);
            if(mutablePair == null){ // 解析数据失败， 响应已处理
                log.error("{}, mutablePair is null ", mutablePair);
                throw new BusinessException("解析数据异常！"); //需要实现类自行抛出ResponseException, 不应该在这抛此异常。
            }
            //解析到订单号
            orderNo = mutablePair.left;
            log.info("解析数据为：orderNo:{}, params:{}", orderNo, mutablePair.getRight());

            //获取订单号 和 订单数据
            Order payOrder = orderServiceImpl.getByOrderNo(orderNo);

            // 订单不存在
            if(payOrder == null){
                log.error("订单不存在. orderNo={} ",orderNo);
                return "fail";
            }

            if (Objects.equals(OrderStatusEnum.PAY_SUCCESS,payOrder.getStatus())){
                return "success";
            }

            //调起接口的回调判断
            payNotifyService.doNotice(request, mutablePair.getRight(), payOrder, PayNotifyService.NoticeTypeEnum.DO_RETURN);

            log.error("=====, 订单通知完成。 orderNo={} =====",orderNo);
            return "success";
        } catch (BusinessException e) {
            log.error("业务处理异常, orderNo={}, BizException:{}", orderNo, e);
            return "fail";

        } catch (Exception e) {
            log.error("回调失败, orderNo={}, 系统异常", orderNo, e);
            return "fail";
        }
    }


}
